package com.boomsecret.unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author wangjinliang on 2019/1/18.
 */
public class UnsafeMonitorDemo {
    private static Unsafe UNSAFE;

    static final int THREAD_COUNT = 10;
    static volatile int count;

    static {
        try {
            Field f = Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            UNSAFE = (Unsafe) f.get(null);
        } catch (Exception e) {
            throw new RuntimeException("init error.");
        }
    }

    public static void main(String[] args) throws Exception {
        Thread[] threads = new Thread[THREAD_COUNT];
        for (int count = 0; count < THREAD_COUNT; count ++) {
            threads[count] = new Thread(() -> {
                for (int index = 0; index < 1000; index ++) {
                    incrementCount();
                }
            });
            threads[count].start();
        }

        for (int count = 0; count < THREAD_COUNT; count ++) {
            threads[count].join();
        }

        System.out.println(count);
    }

    private static void incrementCount() {
        UNSAFE.monitorEnter(THREAD_COUNT);
        count ++;
        UNSAFE.monitorExit(THREAD_COUNT);
    }
}
